﻿using System;
using System.Reflection;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace T3K.SketchEditor.Core {
    public class TagCollection {

        private static TagCollection _instance;
        private List<Tag> _tags = new List<Tag>();

        public List<Tag> Tags {
            get { return _tags; }
        }

        private TagCollection() {

            FileInfo fInfo = new FileInfo(Assembly.GetEntryAssembly().Location);

            string filename = Path.Combine(fInfo.Directory.FullName, "tags");

            if (File.Exists(filename)) {
                StreamReader sr = new StreamReader(File.OpenRead(filename));

                string line;
                while ((line = sr.ReadLine()) != null) {

                    if (line.Trim().StartsWith("!") || line.Trim() == string.Empty)
                        continue;

                    string[] tokens = line.Split('\t');

                    if (tokens.Length < 2)
                        continue;

                    string keyword = null, file = null, type = null, ext = null, parent = null;

                    keyword = tokens[0];
                    file = tokens[1];

                    if (tokens.Length >= 4) type = tokens[3];
                    if (tokens.Length >= 5) ext = tokens[4];

                    if (ext != null) {
                        string[] parentTokens = ext.Split(':');
                        if (parentTokens.Length >= 2) {
                            parent = parentTokens[1];
                            keyword = string.Format("{0}.{1}", parent, keyword);
                        }
                    }

                    if (type != null && type != "d")
                        _tags.Add(new Tag(keyword, file));

                }
            }
        }

        public class Tag {
            string _keyword;
            string _filename;

            public string Filename {
                get { return _filename; }
                set { _filename = value; }
            }

            public string Keyword {
                get { return _keyword; }
                set { _keyword = value; }
            }

            public Tag(string keyword, string filename) {
                this._filename = filename;
                this._keyword = keyword;
            }
        }

        private static object _instanceLocker = new object();
        public static TagCollection Instance {
            get {
                if (_instance == null) {
                    lock (_instanceLocker) {
                        if (_instance == null)
                            _instance = new TagCollection();

                    }
                }
                return _instance;
            }
        }


    }
}
